"""


"""
import time
from flask import current_app, jsonify
from flask import redirect
from flask import request
from flask import session
from flask import url_for

from info import constants, db
from info.models import User, News
from info.utils.response_code import RET
from . import admin_blu
from flask import render_template


@admin_blu.route("/login", methods=["POST", "GET"])
def login():

    if request.method == "GET":
        # 如果已经登录了,并且是管理员身份,就直接重定向到后台首页
        user_id = session.get("user_id", None)
        is_admin = session.get("is_admin", False)
        if user_id and is_admin:  # 如果已经登录了,并且是管理员身份
            # 就直接重定向到后台首页
            return redirect(url_for('admin.index'))
        return render_template("admin/login.html")

    """
    1, 获取参数判空
    2, 查询数据库,看是否有这个用户
    3, 验证密码是否正确
    4, 验证是否是管理员
    5, 保存登录状态  session["is_admin"] = True
    6, 重定向到后台首页
    """
    # 1, 获取参数判空
    data_dict = request.form
    username = data_dict.get("username")
    password = data_dict.get("password")

    if not all([username, password]):
        return render_template("admin/login.html", errmsg="参数错误")
    # 2, 查询数据库,看是否有这个用户
    try:
        user = User.query.filter(User.mobile == username).first()
    except Exception as e:
        current_app.logger.error(e)
        return render_template("admin/login.html", errmsg="数据库查询失败")

    if not user:
        return render_template("admin/login.html", errmsg="用户不存在")
    # 3, 验证密码是否正确
    if not user.check_passowrd(password):
        return render_template("admin/login.html", errmsg="账号或者密码错误")

    # 4, 验证是否是管理员
    if not user.is_admin:
        return render_template("admin/login.html", errmsg="不是管理员用户不能进入后台")
    # 5, 保存登录状态  session["is_admin"] = True
    session["user_id"] = user.id
    session["nick_name"] = user.nick_name
    session["mobile"] = user.mobile
    session["is_admin"] = True
    # 6, 重定向到后台首页
    return redirect(url_for('admin.index'))


@admin_blu.route("/index")
def index():

    return render_template("admin/index.html")


@admin_blu.route("/user_count")
def user_count():
    # 用户总数
    total_count = 0
    try:
        total_count = User.query.filter(User.is_admin != True).count()
    except Exception as e:
        current_app.logger.error(e)

    # 月新增数
    month_count = 0

    t = time.localtime()  # 获取当前系统时间对象

    # time.struct_time(tm_year=2019, tm_mon=1, tm_mday=11, tm_hour=15, tm_min=4, tm_sec=32, tm_wday=4, tm_yday=11,
    #                  tm_isdst=0)
    begin_mon_date_str = '%d-%02d-01' % (t.tm_year, t.tm_mon)
    # 把字符串转换成对象, 之后才可以和create_time进行对比
    from datetime import datetime
    begin_mon_date = datetime.strptime(begin_mon_date_str, "%Y-%m-%d")
    try:
        # month_count = User.query.filter(User.is_admin != True, User.create_time > 本年本月01日00时00分00秒).count()
        month_count = User.query.filter(User.is_admin != True, User.create_time > begin_mon_date).count()
    except Exception as e:
        current_app.logger.error(e)

    # 日新增数
    day_count = 0
    begin_day_date_str = '%d-%02d-%02d' % (t.tm_year, t.tm_mon, t.tm_mday)
    begin_day_date = datetime.strptime(begin_day_date_str, "%Y-%m-%d")
    try:
        # day_count = User.query.filter(User.is_admin != True, User.create_time > 本年本月本日00时00分00秒).count()
        day_count = User.query.filter(User.is_admin != True, User.create_time > begin_day_date).count()
    except Exception as e:
        current_app.logger.error(e)


    # 折线图的处理
    active_count = []
    active_time = []

    # 需求: 查出30天内每一天的用户的登录数量
    begin_day_date_str = '%d-%02d-%02d' % (t.tm_year, t.tm_mon, t.tm_mday)
    begin_day_date = datetime.strptime(begin_day_date_str, "%Y-%m-%d")

    #　先查１天的用户的登录数量
    from datetime import timedelta
    for i in range(0, 30):

        begin_date = begin_day_date - timedelta(days=i)   # 计算出每一天开始的时间点
        end_date = begin_date + timedelta(days=1)   # 计算出每一天结束的时间点
        try:
            # cot = User.query.filter(User.is_admin != True,  本日的00时00分00秒<= User.last_login < 下一天的00时00分00秒).count()
            cot = User.query.filter(User.is_admin != True, User.last_login>=begin_date, User.last_login < end_date).count()
        except Exception as e:
            current_app.logger.error(e)

        active_count.append(cot)
        active_time.append(begin_date.strftime("%Y-%m-%d"))  # 把时间对象转换成字符串,传到模板中

    active_count.reverse()
    active_time.reverse()
    data = {
        "total_count": total_count,
        "month_count": month_count,
        "day_count": day_count,
        "active_count":active_count,
        "active_time":active_time
    }
    return render_template("admin/user_count.html", data=data)



@admin_blu.route("/news_review")
def news_review():

    """
    展示新闻审核列表

    :return:
    """
    # 获取关键字参数
    keyword = request.args.get("keyword", None)

    p = request.args.get("p", 1)
    try:
        p = int(p)
    except Exception as e:
        current_app.logger.error(e)
        p = 1

    news_list = []
    current_page = 1
    total_page = 1

    filters = [News.status != 0]
    if keyword:
        filters.append(News.title.contains(keyword))

    try:
        paginate = News.query.filter(*filters).order_by(News.create_time.desc()).paginate(p,constants.ADMIN_NEWS_PAGE_MAX_COUNT,False)
        news_list = paginate.items
        current_page = paginate.page
        total_page = paginate.pages
    except Exception as e:
        current_app.logger.error(e)

    news_dict_list = []
    for news in news_list:
        news_dict_list.append(news.to_review_dict())

    context = {"total_page": total_page, "current_page": current_page, "news_list": news_dict_list}

    return render_template('admin/news_review.html', data=context)


@admin_blu.route("/news_review_detail/<int:news_id>")
def news_review_detail(news_id):
    """
    展示新闻审核详情页面
    :return:
    """

    # 查询数据库,查询id为news_id的这篇新闻
    try:
        news = News.query.get(news_id)
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.DATAERR,errmsg="数据库错误")

    if not news:
        return jsonify(errno=RET.NODATA,errmsg="没有这篇新闻")

    data={"news":news.to_dict()}
    return render_template("admin/news_review_detail.html", data =data)


@admin_blu.route("/news_review_action", methods=["POST"])
def news_review_action():
    """
    处理  提交审核结果的  请求

    # 1. 接受参数(两个参数  new_id, action的值如果是accept就通过，如果是reject就拒绝通过，拒绝的情况下再获取一个参数reason)
    # 2. 参数校验
    # 3、查询新闻是否存在
    # 4、判断action的值进行 执行对应操作(修改news.status 通过为0，不通过为-1)
    # 5、提交数据
    """
    # 1. 接受参数(两个参数  new_id, action的值如果是accept就通过，如果是reject就拒绝通过，拒绝的情况下再获取一个参数reason)
    data_dict = request.json
    action = data_dict.get("action")
    news_id = data_dict.get("news_id")
    # 2. 参数校验
    if not all([action, news_id]):
        return jsonify(errno=RET.PARAMERR, errmsg="参数错误")
    if action not in ("accept", "reject"):
        return jsonify(errno=RET.PARAMERR, errmsg="参数错误")

    # 3、查询新闻是否存在
    try:
        news = News.query.get(news_id)
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.DATAERR, errmsg="数据库错误")

    if not news:
        return jsonify(errno=RET.NODATA, errmsg="没有这篇新闻")

    # 4、判断action的值进行 执行对应操作(修改news.status 通过为0，不通过为-1)
    if action == "accept":
        news.status = 0
    else:
        # 拒绝通过的时候,要多获取一个参数, 拒绝原因
        reason = data_dict.get("reason")
        if not reason:
            return jsonify(errno=RET.PARAMERR,errmsg="参数错误")

        news.reason = reason
        news.status = -1
    try:
        db.session.commit()
    except Exception as e:
        current_app.logger.error(e)
        db.session.rollback()
        return jsonify(errno=RET.DBERR,errmsg="数据库操作错误")

    # 5、提交数据
    return jsonify(errno=RET.OK, errmsg="操作成功")